package cs5226.actions;


import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

import cs5226.util.*;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements  ServletRequestAware {

	private static final long serialVersionUID = 1L;
	private HttpServletRequest request = null;
	
	@Override 
	public String execute() throws Exception {
		boolean isAuthenticated = false;
	
		try {
			String userid = request.getParameter("userid");
			String pwd = request.getParameter("pwd");
			
			if(!StringUtil.isNullOrBlank(userid) && Constants.USER_ID.equalsIgnoreCase(userid.trim()) && Constants.PASSWORD.equals(pwd)){
				isAuthenticated = true;
				request.getSession().setAttribute("loggedIn", userid);
			}else if(!StringUtil.isNullOrBlank(userid)){
				request.setAttribute("msg", "Login failed due to invalid user name/password.");
			}
					
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", e.getMessage());
		}
	
		if(isAuthenticated)
			return super.SUCCESS;
		else
			return super.LOGIN;
	}
	
	
	public String logout() throws Exception {
		
		request.getSession().removeAttribute("loggedIn");
		
		return super.SUCCESS;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
	}
}